let vm =new Vue({
   el:"#app",
      // 修改Vue读取变量的语法，防止与jinja2混淆
    delimiters: ['[[', ']]'],
    data:function (){
       return {
         username:'',
         password:'',
         password2:'',
         mobile:'',
         imageCode:'',
         smsCode:'',
         allow:false,
         error_name:'',
         error_password:'',
         error_password2:'',
         error_mobile:'',
         error_image:'',
         error_sms:'',
         error_allow: '',
         image_code_url:'',
         uuid:'',
         sms_tip:'获取短信验证码',
         send_sms_flag:false, //是否已经发送过短信，避免恶意发送请求
       }
    },
    mounted(){
      this.generate_image_code()
    },
    methods:{
       //生成图形验证码
       generate_image_code(){
         this.uuid = generateUUID()
         this.image_code_url = `/image_code/${this.uuid}/`

       },
        // 手机验证码倒计时
        count_down(time){

          let timer = setInterval( ()=>{
              if (time ==0) {

                  this.sms_tip = '重新发送'
                  clearInterval(timer)
                  // 重新生成图形验证码
                   this.generate_image_code()
                  // 时间到，表示可以重新发送短信
                  this.send_sms_flag = false
                  return
              }


             this.sms_tip = `${time}秒`
              time--

          },1000)
        },
        // 请求发送短信
        send_sms_code(){
           if (this.send_sms_flag) return
           this.vaildFiled('mobile')
            this.vaildFiled('imageCode')
           if (this.error_mobile == '' && this.error_image == '' ){
                //锁住发送短信方法，直到计时器结束
               this.send_sms_flag = true
             axios
                 .get(`/sms_codes/${this.mobile}/?image_code=${this.imageCode}&uuid=${this.uuid}`,
                     {responseType: 'json'})
                 .then(res=>{
                     res = res.data;
                     if (res.code == "0"){
                        // 设置计时器
                       const time = 60
                        this.count_down(time)
                     }else {
                         if (res.code == '4001'){
                             this.error_image = res.err_msg
                         }
                         if (res.code == '4007'){
                             this.error_mobile = res.err_msg
                         }
                         if (res.code = '4002'){
                             this.error_sms = res.err_msg
                         }
                         this.generate_image_code()
                         //如果没有进入倒计时，则解封
                         this.send_sms_flag = false
                     }
                 })
                 .catch(err => {
                     //如果没有进入倒计时，则解封
                         this.send_sms_flag = false
                 })

           }

        },
       //校验字段
       vaildFiled(type){
        const vaildObj = {
            'username': async  function (){
                let re = /^[a-zA-Z0-9_-]{5,20}$/;
               if(!re.test(this.username.trim())){
                   this.error_name = '请输入5-20个字符的用户';
                   return;
               }
               if (!await this.checkUsername()){
                     this.error_name = '该用户名已被注册';
                     return;
               }


               this.error_name =''
            },
            'password':function (){
                 let re = /^[0-9A-Za-z]{8,20}$/;
               if(!re.test(this.password.trim())){
                   this.error_password = '请输入8-20位的密码';
                   return
               }

               this.error_password=''
            },
            'password2':function (){
               if(this.password2.trim() === ''){
                   this.error_password2 = '请再次输入密码';
                   return
               }
               if (this.password2.trim() != this.password.trim()){
                    this.error_password2 = '两次输入的密码不一致';
                    return;
               }
               this.error_password2=''
            },
            'mobile': async function (){
                  let re = /^1[3-9]\d{9}$/;
                 if( !re.test(this.mobile.trim())){
                   this.error_mobile = '请输入正确的手机号码';
                   return
                 }

                 if (!await this.checkMobile()){
                      this.error_mobile  = '该手机号已被注册';
                     return;
                 }
                 this.error_mobile = ''
            },
            'imageCode':function (){
               if(this.imageCode.trim() === ''){
                   this.error_image = '请填写图形验证码';
                   return
                }
                this.error_image = ''
            },
            'smsCode':function (){
                 if(this.smsCode.trim() === ''){
                   this.error_sms = '请填写短信验证码';
                   return
                }
                 this.error_sms = ''
            },
            'allow':function (){
                console.log(this.allow)
                if (!this.allow){
                  this.error_allow = '请勾选用户协议'
                    return
                }
                 this.error_allow = ''
            }
        }
        //改变函数this作用域
        vaildObj[type].call(this)
     },
       //提交表单
       handleSubmit(e){

           let vaildFileds = ['username','password','password2','mobile','imageCode','smsCode','allow']
            vaildFileds.forEach((item)=>{

                this.vaildFiled(item)
            })
            if (this.error_name.trim() != '' ||
                this.error_password.trim() != ''||
                this.error_password2.trim() != ''||
                this.error_mobile.trim() != ''||
                this. error_image.trim() !=''||
                this.error_sms.trim() !=''||
                this.error_allow.trim() !=''
            ){

               // 禁用表单的提交
            e.preventDefault();
            }
        },
        //检查用户名
       async checkUsername(){
         let  res =  await  axios.get("/usernames/"+this.username+"/count/",{responseType: 'json'})
          res = res.data;
           if (res.code == '0' && res.data.count == 0){
               return true
           }
            return false
        },
        // 检查手机号是否重复
      async  checkMobile(){
           let res =  await axios.get("/mobiles/"+this.mobile+"/count/",{responseType: 'json'})
           res = res.data;
           if (res.code == '0' && res.data.count == 0){
               return true
           }
            return false
        }

    }
})
